package com.secsbrain.development.dal.config;

import com.secsbrain.development.feign.SbCachingSpringLoadBalancerFactory;
import com.secsbrain.development.feign.SbLoadBalancerFeignClient;
import feign.Client;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class SbFeignLoadBalancedConfiguration {

    @Bean
    @Primary
    @ConditionalOnMissingBean
    @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
    public SbCachingSpringLoadBalancerFactory carrierCachingLBClientFactory(SpringClientFactory factory) {
        return new SbCachingSpringLoadBalancerFactory(factory);
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean
    @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
    public SbCachingSpringLoadBalancerFactory carrierRetryabeCachingLBClientFactory(
            SpringClientFactory factory,
            LoadBalancedRetryFactory retryFactory) {
        return new SbCachingSpringLoadBalancerFactory(factory, retryFactory);
    }


    @Bean
    @Primary
    @ConditionalOnMissingBean
    public Client feignClient(SbCachingSpringLoadBalancerFactory cachingFactory,
                              SpringClientFactory clientFactory) {
        return new SbLoadBalancerFeignClient(new Client.Default(null, null),
                cachingFactory, clientFactory);
    }
}
